package file_tab

import (
	"fmt"
	"strings"

	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"
	"file_explorer/service"
	"file_explorer/service/eventbus"
	"file_explorer/service/task"
	"file_explorer/service/third_program"
	"file_explorer/view/packed_widgets"
	"file_explorer/view/store"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

type Toolbar struct {
	*fyne.Container

	createFileButton      *packed_widgets.Button // 新建文件按钮
	deleteFileButton      *packed_widgets.Button // 删除文件按钮
	addFavoritesButton    *packed_widgets.Button // 添加收藏按钮
	deleteFavoritesButton *packed_widgets.Button // 取消收藏按钮
	addOpListButton       *packed_widgets.Button // 添加操作列表按钮
	copyButton            *packed_widgets.Button // 复制按钮
	moveButton            *packed_widgets.Button // 移动按钮
	filterButton          *packed_widgets.Button // 过滤按钮
	filterWindow          *FilterWindow          // 过滤菜单
	urlButton             *packed_widgets.Button // url按钮
	editMetadataButton    *packed_widgets.Button // 编辑元数据按钮

	tabCtx *store.FileTabContext
}

func (toolbar *Toolbar) RefreshData() {
	curPath := toolbar.tabCtx.GetPath()

	// 收藏/取消收藏 显示
	if toolbar.tabCtx.GetGlobalConf().FindFavorites(curPath) >= 0 {
		toolbar.getAddFavoritesButton().Hide()
		toolbar.getDeleteFavoritesButton().Show()
	} else {
		toolbar.getAddFavoritesButton().Show()
		toolbar.getDeleteFavoritesButton().Hide()
	}

	// 编辑元数据、打开url按钮 显示
	if len(toolbar.tabCtx.CheckedList) > 0 {
		toolbar.getEditMetadataButton().Enable()
		toolbar.getUrlButton().Enable()
		toolbar.getDeleteFileButton().Enable()
		toolbar.getAddOpListButton().Enable()
	} else {
		toolbar.getEditMetadataButton().Disable()
		toolbar.getUrlButton().Disable()
		toolbar.getDeleteFileButton().Disable()
		toolbar.getAddOpListButton().Disable()
	}
}

// 获取新建文件按钮
func (toolbar *Toolbar) getCreateFileButton() *packed_widgets.Button {
	if toolbar.createFileButton != nil {
		return toolbar.createFileButton
	}

	toolbar.createFileButton = packed_widgets.NewButton("新建", theme.FolderNewIcon(), func() {
		// 添加context，回调 创建tab
		fileCreateTabContext := store.NewFileCreateTabContext(toolbar.tabCtx)
		toolbar.tabCtx.GetGlobalContext().AddTab(fileCreateTabContext)
	})

	return toolbar.createFileButton
}

func (toolbar *Toolbar) getDeleteFileButton() *packed_widgets.Button {
	if toolbar.deleteFileButton != nil {
		return toolbar.deleteFileButton
	}

	toolbar.deleteFileButton = packed_widgets.NewButton("删除", theme.DeleteIcon(), func() {
		info := fmt.Sprintf("删除选中%d项", len(toolbar.tabCtx.CheckedList))
		dialog.ShowConfirm("确认", info,
			func(confirm bool) {
				if !confirm {
					return
				}
				log.Info("删除文件%d项，路径：%s", len(toolbar.tabCtx.CheckedList), toolbar.tabCtx.GetPath())
				failedFiles := make([]string, 0, len(toolbar.tabCtx.CheckedList))
				for _, fileInfo := range toolbar.tabCtx.CheckedList {
					err := service.DeleteFile([]*model.FileInfo{fileInfo})
					if err != nil {
						failedFiles = append(failedFiles, fileInfo.GetPath())
					}
				}
				if len(failedFiles) > 0 {
					packed_widgets.NotifyError("删除文件失败，文件数：%d，路径：%s", len(failedFiles), toolbar.tabCtx.GetPath())
				}
				toolbar.tabCtx.GetGlobalContext().RefreshTabIfExists(toolbar.tabCtx.GetPath())
			},
			packed_widgets.GetAppWindow())
	})

	return toolbar.deleteFileButton
}

// 获取标签过滤按钮
func (toolbar *Toolbar) getFilterButton() *packed_widgets.Button {
	if toolbar.filterButton != nil {
		return toolbar.filterButton
	}

	toolbar.filterButton = packed_widgets.NewButton("过滤", theme.DocumentPrintIcon(), nil)

	toolbar.filterButton.OnTapped = func() {
		if toolbar.filterWindow == nil {
			toolbar.filterWindow = newFilterWindow(toolbar.tabCtx)
			// 过滤器窗口关闭时清空过滤选项
			toolbar.filterWindow.SetOnClosed(func() {
				log.Info("过滤器窗口关闭，路径：%s", toolbar.tabCtx.GetPath())
				toolbar.filterWindow = nil
				toolbar.tabCtx.ResetFilters()
			})
		}
		toolbar.filterWindow.Toggle()
	}

	return toolbar.filterButton
}

// 获取url按钮
func (toolbar *Toolbar) getUrlButton() *packed_widgets.Button {
	if toolbar.urlButton != nil {
		return toolbar.urlButton
	}

	toolbar.urlButton = packed_widgets.NewButton("打开url", theme.DocumentPrintIcon(), nil)
	toolbar.urlButton.OnTapped = func() {
		urls := make([]string, len(toolbar.tabCtx.CheckedList))
		for i, fileInfo := range toolbar.tabCtx.CheckedList {
			urls[i] = fileInfo.GetUrl()
			urls[i] = util.ReplaceWildcard(urls[i], map[string]string{"name": fileInfo.Name})
		}
		log.Info("打开url，链接：%s", strings.Join(urls, ", "))
		third_program.GetCaller().OpenUrlsWithDefaultWebExplorer(urls)
	}

	return toolbar.urlButton
}

// 获取添加收藏夹按钮
func (toolbar *Toolbar) getAddFavoritesButton() *packed_widgets.Button {
	if toolbar.addFavoritesButton != nil {
		return toolbar.addFavoritesButton
	}

	toolbar.addFavoritesButton = packed_widgets.NewButton("收藏", theme.StorageIcon(), func() {
		nameEntry := widget.NewEntry()
		nameEntry.Text = toolbar.tabCtx.GetDirName()
		dialog.ShowForm("收藏", "确认", "取消",
			[]*widget.FormItem{
				widget.NewFormItem("名称", nameEntry),
			},
			func(confirm bool) {
				if !confirm || len(nameEntry.Text) == 0 {
					return
				}
				curPath := toolbar.tabCtx.GetPath()
				toolbar.tabCtx.GetGlobalConf().AddFavorites(curPath, nameEntry.Text)
				err := toolbar.tabCtx.UpdateGlobalConf(model.ConfKeyFavorites, toolbar.tabCtx.GetGlobalConf().Favorites)
				if err != nil {
					packed_widgets.NotifyError("添加收藏失败，路径：%s，错误: %s", curPath, err)
					return
				}
				log.Info("添加收藏成功，路径：%s", curPath)
				toolbar.RefreshData()
			},
			packed_widgets.GetAppWindow())
	})

	return toolbar.addFavoritesButton
}

// 获取取消收藏按钮
func (toolbar *Toolbar) getDeleteFavoritesButton() *packed_widgets.Button {
	if toolbar.deleteFavoritesButton != nil {
		return toolbar.deleteFavoritesButton
	}

	toolbar.deleteFavoritesButton = packed_widgets.NewButton("取消收藏", theme.StorageIcon(), func() {
		curPath := toolbar.tabCtx.GetPath()
		toolbar.tabCtx.GetGlobalConf().DeleteFavorites(curPath)
		err := toolbar.tabCtx.UpdateGlobalConf(model.ConfKeyFavorites, toolbar.tabCtx.GetGlobalConf().Favorites)
		if err != nil {
			packed_widgets.NotifyError("取消收藏失败，路径：%s，错误: %v", curPath, err)
			return
		}
		log.Info("取消收藏成功，路径：%s", curPath)
		toolbar.RefreshData()
	})

	return toolbar.deleteFavoritesButton
}

// 获取添加操作列表按钮
func (toolbar *Toolbar) getAddOpListButton() *packed_widgets.Button {
	if toolbar.addOpListButton != nil {
		return toolbar.addOpListButton
	}

	toolbar.addOpListButton = packed_widgets.NewButton("批量操作", theme.ContentPasteIcon(), func() {
		toolbar.tabCtx.GetGlobalContext().OpListContext.AddFileInfos(toolbar.tabCtx.CheckedList)
		log.Info("添加%d项到操作列表", len(toolbar.tabCtx.CheckedList))
	})

	return toolbar.addOpListButton
}

// 获取复制按钮
func (toolbar *Toolbar) getCopyButton() *packed_widgets.Button {
	if toolbar.copyButton != nil {
		return toolbar.copyButton
	}

	toolbar.copyButton = packed_widgets.NewButton("复制", theme.ContentPasteIcon(), func() {
		dstDir := toolbar.tabCtx.GetPath()
		checkedList := toolbar.tabCtx.GetGlobalContext().OpListContext.CheckedList
		copyTask := task.NewBatchCopier(checkedList, dstDir)
		toolbar.tabCtx.GetGlobalContext().TaskManager.SubmitGlobalTask(copyTask)
		copyTask.SetOnFinish(func(costTime int64, ok bool, err error) {
			if ok && err == nil {
				packed_widgets.NotifyInfo("任务完成: %s", copyTask.GetLabel())
				toolbar.tabCtx.GetGlobalContext().OpListContext.DeleteFileInfos(checkedList)
			} else if err != nil {
				packed_widgets.NotifyError("任务失败: %s，错误：%s", copyTask.GetLabel(), err.Error())
			}
			toolbar.tabCtx.GetGlobalContext().TaskManager.DeleteGlobalTask(copyTask)
			toolbar.tabCtx.GetGlobalContext().RefreshTabIfExists(dstDir)
		})
	})
	if len(toolbar.tabCtx.GetGlobalContext().OpListContext.CheckedList) == 0 {
		toolbar.copyButton.Disable()
	}

	return toolbar.copyButton
}

// 获取移动按钮
func (toolbar *Toolbar) getMoveButton() *packed_widgets.Button {
	if toolbar.moveButton != nil {
		return toolbar.moveButton
	}

	toolbar.moveButton = packed_widgets.NewButton("移动", theme.ContentPasteIcon(), func() {
		dstDir := toolbar.tabCtx.GetPath()
		checkedList := toolbar.tabCtx.GetGlobalContext().OpListContext.CheckedList
		moveTask := task.NewBatchMover(checkedList, dstDir)
		toolbar.tabCtx.GetGlobalContext().TaskManager.SubmitGlobalTask(moveTask)
		moveTask.SetOnFinish(func(costTime int64, ok bool, err error) {
			if ok && err == nil {
				packed_widgets.NotifyInfo("任务完成: %s", moveTask.GetLabel())
				toolbar.tabCtx.GetGlobalContext().OpListContext.DeleteFileInfos(checkedList)
			} else if err != nil {
				packed_widgets.NotifyError("任务失败: %s，错误：%s", moveTask.GetLabel(), err.Error())
			}
			toolbar.tabCtx.GetGlobalContext().TaskManager.DeleteGlobalTask(moveTask)
			toolbar.tabCtx.GetGlobalContext().RefreshTabIfExists(dstDir)
		})
	})
	if len(toolbar.tabCtx.GetGlobalContext().OpListContext.CheckedList) == 0 {
		toolbar.moveButton.Disable()
	}

	return toolbar.moveButton
}

// 获取修改元数据按钮
func (toolbar *Toolbar) getEditMetadataButton() *packed_widgets.Button {
	if toolbar.editMetadataButton != nil {
		return toolbar.editMetadataButton
	}

	toolbar.editMetadataButton = packed_widgets.NewButton("修改元数据", theme.DocumentCreateIcon(), func() {
		editMetadataTabContext := store.NewMetadataTabContext(toolbar.tabCtx)
		if editMetadataTabContext == nil {
			return
		}
		toolbar.tabCtx.GetGlobalContext().AddTab(editMetadataTabContext)
	})

	return toolbar.editMetadataButton
}

func NewToolbar(tabCtx *store.FileTabContext, fileTab *FileTab) *Toolbar {
	toolbar := &Toolbar{
		tabCtx: tabCtx,
	}

	toolbar.Container = container.NewVBox(
		widget.NewToolbar(
			packed_widgets.NewButton("", theme.ComputerIcon(), func() {
				third_program.GetCaller().OpenPathWithDefaultFileExplorer(toolbar.tabCtx.GetPath())
			}),
			widget.NewToolbarSeparator(),
			toolbar.getAddFavoritesButton(),
			toolbar.getDeleteFavoritesButton(),
			widget.NewToolbarSeparator(),
			toolbar.getCreateFileButton(),
			toolbar.getDeleteFileButton(),
			widget.NewToolbarSpacer(),
			toolbar.getCopyButton(),
			toolbar.getMoveButton(),
			toolbar.getAddOpListButton(),
		),
		widget.NewToolbar(
			toolbar.getUrlButton(),
			toolbar.getFilterButton(),
			toolbar.getEditMetadataButton(),
			widget.NewToolbarSpacer(),
			fileTab.FileList.Checklist.GetReverseButton(),
			fileTab.FileList.Checklist.GetRangeButton(),
		),
	)

	toolbar.tabCtx.GetGlobalContext().OpListContext.RegisterConsumer(
		eventbus.EventKeyOpListCtxChecklistChange,
		func(event *model.Event) {
			if len(toolbar.tabCtx.GetGlobalContext().OpListContext.CheckedList) > 0 {
				toolbar.getCopyButton().Enable()
				toolbar.getMoveButton().Enable()
				return
			}
			toolbar.getCopyButton().Disable()
			toolbar.getMoveButton().Disable()
		},
	)

	return toolbar
}
